<template>
  <el-dialog
    :title="title"
    :visible.sync="isShowDialog"
    center
    :destroy-on-close="true"
    @close="closeFn"
  >
    <el-form ref="deptForm" label-width="100px" :label-position="labelPosition" :model="formData" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="formData.name" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="formData.code" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="formData.manager" placeholder="请选择" @blur="checkSelect">
          <el-option
            v-for="user in employeeList"
            :key="user.id"
            :label="user.username"
            :value="user.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="formData.introduce" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="isShowDialog = false">取 消</el-button>
      <el-button type="primary" @click="addDepartmentFn">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getDepartmentList, addDepartment, getDepartmentDetail, editDepartmentDetail } from '@/api/department'
import { getEmployeeList } from '@/api/employee'
export default {
  props: {
    treeNode: {
      type: Object,
      required: true
    }
  },
  data() {
    // 自定义校验部门名称 val为输入的值
    const checkRepeatName = async(rules, val, callback) => {
      const { depts } = await getDepartmentList()
      let isRepeat
      if (this.formData.id) {
        // 编辑
        isRepeat = depts.filter(item => item.pid === this.treeNode.pid)
          .some(item => item.name === val && item.id !== this.treeNode.id)
      } else {
        // 新增
        isRepeat = depts.filter(item => item.pid === this.treeNode.id)
          .some(item => item.name === val)
      }

      if (isRepeat) {
        callback(new Error('部门名称已存在'))
      } else {
        callback()
      }
    }
    // 自定义校验部门编码
    const checkRepeatCode = async(rules, val, callback) => {
      const { depts } = await getDepartmentList()
      let isRepeat
      // 校验编码是否存在，编码唯一，所以跟所有的数据进行判断
      if (this.formData.id) {
        // 编辑
        isRepeat = depts.some(item => item.code === val && item.code !== this.treeNode.code)
      } else {
        // 添加
        isRepeat = depts.some(item => item.code === val)
      }
      isRepeat ? callback(new Error('部门编码已存在')) : callback()
    }
    return {
      isShowDialog: false,
      employeeList: [],
      title: '',
      labelPosition: 'right',
      formData: {
        name: '',
        code: '',
        manager: '',
        introduce: '',
        pid: ''
      },
      rules: {
        name: [{ required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { validator: checkRepeatName, trigger: 'blur' }],
        code: [{ required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
          { validator: checkRepeatCode, trigger: 'blur' }],
        manager: [{ required: true, message: '部门负责人不能为空', trigger: 'blur' }],
        introduce: [{ required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { trigger: 'blur', min: 1, max: 300, message: '部门介绍要求1-50个字符' }]
      }
    }
  },
  async created() {
    // 获取员工列表
    this.employeeList = await getEmployeeList()
    // console.log(this.employeeList)
  },
  methods: {
    // 失焦校验下拉选择框
    checkSelect() {
      // console.log(66)
      // this.$refs.deptForm.validateField('manager')
      setTimeout(() => {
        // console.log(101, this.$refs.deptForm)
        this.$refs.deptForm.validateField('manager')
      }, 100)
    },
    // 新增/编辑部门
    async addDepartmentFn() {
      // 请求之前进行表单校验，防止啥都不输入
      await this.$refs.deptForm.validate()
      // 判断时新增还是编辑
      if (this.treeNode.id) {
        // 发起编辑请求
        await editDepartmentDetail(this.treeNode.id)
        this.$message.success('编辑部门成功')
      } else {
        // 发起新增请求
        await addDepartment({
          ...this.formData, pid: this.treeNode.id
        })
        // 提示
        this.$message.success('新增部门成功')
      }

      // 清空表单
      this.$refs.deptForm.resetFields()
      // 关闭弹窗
      this.isShowDialog = false
      // 通知父组件
      this.$emit('addDepartmentSuccess')
    },
    closeFn() {
      this.formData = {
        name: '',
        code: '',
        manager: '',
        introduce: '',
        pid: '',
        id: ''
      }
      this.$refs.deptForm.resetFields()
    },
    // 获取部门详情
    async getDepartmentDetail(id) {
      // 发请求
      this.formData = await getDepartmentDetail(id)
    }
  }
}
</script>

<style >
.el-dialog{
-webkit-box-shadow:none;
box-shadow: none;
}
</style>
